package home.game.client.display.panels;

import home.game.client.controllers.BoardController;
import home.game.client.controllers.Controllable;
import home.game.client.display.models.PlayerType;
import home.game.client.display.models.Tile;
import home.game.entity.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Observable;

/**
 */
public class GamePanel extends Observable implements Controllable {
    public static final int BOARD_SIZE = 9;
    private JPanel gamePanel;
    private Tile[] board;
    private BoardController controller;
    private boolean isInitialized;

    public boolean isInitialized() {
        return isInitialized;
    }

    public void initPanel(User user) {
        gamePanel = new JPanel(new GridLayout(3, 3));
        controller = new BoardController(user);
        board = new Tile[BOARD_SIZE];

        controller.initController(board);

        for (int i = 0; i < BOARD_SIZE; i++) {
            board[i] = new Tile();
            board[i].initTile();
            board[i].addObserver(controller);
            board[i].getPanel().addMouseListener(new InputListener(board[i]));
            gamePanel.add(board[i].getPanel());
        }
        isInitialized = true;
    }

    public JPanel getGamePanel() {
        return gamePanel;
    }

    private class InputListener extends MouseAdapter {
        private Tile tile;

        public InputListener(Tile tile) {
            this.tile = tile;
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            if (tile.getTileObject() == null && controller.getInControl() == PlayerType.Player) {
                tile.setOwner(PlayerType.Player);
                tile.setTileObject(controller.getInControlIcon());

            }
        }
    }

}
